package dk.dtu.android.transport.gps;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import dk.dtu.android.transport.Constants;
import dk.dtu.android.transport.Helpers;
import dk.dtu.android.transport.db.KeyValueTable;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class GPSAlarmReceiver extends BroadcastReceiver {

	public final static int REQUEST_ID = 287328;
	public final static String DEFAULT_INTERVAL = "60";
	
	public static PendingIntent alarmSender;
	public static Context context;
	public static boolean isSet = false;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		GPSService.serviceStarter(context);
	}
	
	public static boolean isAlarmSet(Context context)
	{
		if (alarmSender != null && isSet){
			return true;
		}
		else {
			return false;
		}
	}
	
	public static void initialize(Context context)
	{
		GPSAlarmReceiver.context = context;
	}
	
	public static long nextLog()
	{
		String lastLog = KeyValueTable.getValue(Constants.LAST_GPS_LOG);
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MINUTE, 1);
		long nowMilli = cal.getTimeInMillis();
        if (lastLog == null)
        {
        	// Has never been logged
        	return nowMilli;
        }
        else
        {
        	try {
        		int defaultInterval = Integer.parseInt(KeyValueTable.getValue(Constants.LOCATION_INTERVAL, DEFAULT_INTERVAL));
				Date lastLogDate = Helpers.ToDate(lastLog);
				Date now = new Date();
				cal.setTime(lastLogDate);
				cal.add(Calendar.MINUTE, defaultInterval);
				if (cal.getTime().before(now))
				{
					return nowMilli;
				}
				else
				{
					return cal.getTimeInMillis();
				}
			} catch (ParseException e) {
				return nowMilli;
			}
        }
	}
	
	public static void startAlarm()
	{
		if (alarmSender == null || !isSet)
		{
			Log.d("GPSAlarmReceiver", "Starting GPSAlarmReceiver!");
	        Intent intent = new Intent(context, GPSAlarmReceiver.class);
	        alarmSender = PendingIntent.getBroadcast(context, GPSAlarmReceiver.REQUEST_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	
	        // Get the AlarmManager service
	        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	        am.setRepeating(
	        	AlarmManager.RTC_WAKEUP,
	        	nextLog(),
	        	Integer.parseInt(KeyValueTable.getValue(Constants.LOCATION_INTERVAL, DEFAULT_INTERVAL))*60*1000, 
	        	alarmSender
	        );
	        isSet = true;
		}
		else
		{
			Log.d("GPSAlarmReceiver", "GPSAlarmReceiver is already started!");
		}
	}
	
	public static void updateAlarm()
	{
		if (isSet)
		{
			Log.d("GPSAlarmReceiver", "Updating GPSAlarmReceiver!");
			Intent intent = new Intent(context, GPSAlarmReceiver.class);
			if (alarmSender == null)
			{
				alarmSender = PendingIntent.getBroadcast(context, GPSAlarmReceiver.REQUEST_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			}
			Toast.makeText(context, "Updating alarm...", Toast.LENGTH_LONG).show();
			AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	        am.set(
	        	AlarmManager.RTC,
	        	nextLog(),
	        	//Integer.parseInt(KeyValueTable.getValue(Constants.LOCATION_INTERVAL, DEFAULT_INTERVAL))*60*1000, 
	        	alarmSender
	        );
		}
	}
	
	public static void stopAlarm()
	{
		Log.d("GPSAlarmReceiver", "Stopping GPSAlarmReceiver!");
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(alarmSender);
        isSet = false;
        
	}
}
